package net.homeftp.heimo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import net.homeftp.heimo.common.ExternalStorageFileHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ChooseImageActivity extends Activity {
	private final String TAG = "ChooseImageActivity";
	ImageView chosenImageView, previewImageView;
	Button choosePicture, loadPicture, chopPicture, delPicture;
	TextView chooseImgURI, previewImgURI;
	Uri imageUri;
	private final int CHOOSE = 0;
	private final int CHOP = 1;
	private final int PREVIEW = 2;

	private String fileName = "test.bmp";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_view_layout);
		chooseImgURI = (TextView) this.findViewById(R.id.chooseUri);
		previewImgURI = (TextView) this.findViewById(R.id.previewUri);

		chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView);
		previewImageView = (ImageView) this.findViewById(R.id.PreviewImageView);

		loadPicture = (Button) this.findViewById(R.id.LoadPictureButton);
		choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton);
		chopPicture = (Button) this.findViewById(R.id.ChopPictureButton);
		delPicture = (Button) this.findViewById(R.id.DelPictureButton);

	}

	/*
	 * INTERNAL_CONTENT_URI EXTERNAL_CONTENT_URI
	 */
	public void fnChoose(View v) {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(Intent.createChooser(i, "Select Image"), CHOOSE);
		// startActivityForResult(i, CHOOSE);
	}

	/*
	 * Save Uri into preference as String
	 * http://stackoverflow.com/questions/7169485
	 * /how-to-use-sharepreference-to-save-a-uri-or-any-storage
	 */
	public void fnChop(View v) {
		if (imageUri != null) {
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			// indicate image type and Uri
			cropIntent.setDataAndType(imageUri, "image/*");
			// set crop properties
			cropIntent.putExtra("crop", "true");
			// indicate aspect of desired crop
			cropIntent.putExtra("aspectX", 1);
			cropIntent.putExtra("aspectY", 1);
			// indicate output X and Y
			cropIntent.putExtra("outputX", 100);
			cropIntent.putExtra("outputY", 100);
			// retrieve data on return
			cropIntent.putExtra("return-data", true);
			// start the activity - we handle returning in onActivityResult
			// startActivityForResult(cropIntent, CHOP);
			startActivityForResult(
					Intent.createChooser(cropIntent, "Chop Image"), CHOP);
		} else {
			Toast.makeText(this, "Please choose an Image...", Toast.LENGTH_LONG)
					.show();
		}
	}

	public void fnLoad(View v) {
		// if (imageUri != null) {
		// previewImageView.setImageURI(imageUri);
		// }
		// File f = new File(getFilesDir(), fileName);
		// Bitmap lbm = BitmapFactory.decodeFile(f.getPath());
		// previewImageView.setImageBitmap(lbm);
		// Log.i(TAG, "Load img from f:" + f);
		FileInputStream in;
		try {
			in = openFileInput(fileName);
			Bitmap lbm = BitmapFactory.decodeStream(in);
			previewImageView.setImageBitmap(lbm);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Toast.makeText(this, "Error Loading Image...", Toast.LENGTH_LONG)
					.show();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_OK) {
			Log.i(TAG, "requestCode:" + requestCode);
			switch (requestCode) {
			case CHOOSE:
				fnChooseImage(intent);
				break;
			case CHOP:
				fnChopImage(intent);
				break;
			case PREVIEW:
				break;
			}
		} else {
			Log.i(TAG, "Request Fail code :" + requestCode);
		}
	}

	private void fnChopImage(Intent i) {
		// Uri uri = imageUri = i.getData();

		Bundle extras = i.getExtras();
		// get the cropped bitmap
		Bitmap bm = extras.getParcelable("data");

		// previewImgURI.setText(uri.getPath());
		previewImageView.setImageBitmap(bm);
		fnSaveImage(bm);
	}

	private void fnSaveImage(Bitmap bm) {
		ExternalStorageFileHelper esFile = new ExternalStorageFileHelper(this);
		esFile.saveBitmap(fileName, bm);
	}

	public void fnDelete(View v) {
		ExternalStorageFileHelper esFile = new ExternalStorageFileHelper(this);
		esFile.delFile(fileName);
	}

	private void fnChooseImage(Intent intent) {
		imageUri = intent.getData();
		String uriText = imageUri.getPath();
		chooseImgURI.setText(uriText);

		Display currentDisplay = getWindowManager().getDefaultDisplay();
		int dw = currentDisplay.getWidth();
		int dh = currentDisplay.getHeight() / 2 - 100;
		try {
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageUri), null, bmpFactoryOptions);
			bmpFactoryOptions.inSampleSize = 4;
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageUri), null, bmpFactoryOptions);
			chosenImageView.setImageBitmap(bmp);
		} catch (FileNotFoundException e) {
			Log.v("ERROR", e.toString());
		}
	}
}
